<?php
#
# UNLVSpatial: a dmBridge module for spatial content
#
# Copyright © 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Used in the context of the HTTP API. (routes.xml describes how its methods
 * are hooked up to URIs.)
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class UNLVSpatialController extends DMTEObjectController {

	public function apiSearch() {
		$query = $this->getQueryFromURI(DMHTTPRequest::getCurrent()->getURI());

		$response = new DMHTTPResponse();
		$rep = DMHTTPResponseFactory::getRepresentation();
		$response->setRepresentation($rep);
		try {
			$trans = DMHTTPResponseFactory::getTransformer();
			$rep->setBody($trans->transformSpatialResults($query));
		} catch (DMException $e) {
			$response->setStatusCode($e->getHTTPResponseCode());
			$rep->setBody($e->getMessage());
		}
		$response->send();
		die;
	}

	/**
	 * @Override
	 */
	public function index($alias) {
		$alias = DMCollection::getSanitizedAlias($alias);
		if (strlen($alias) < 2) {
			$alias = "/dmdefault";
		}

		try {
			$ts = $this->getTemplateSet();
			if (!$ts) {
				throw new DMUnavailableModelException(
						DMLocalizedString::getString("INVALID_TPL_SET"));
			}

			$specified_collection = DMCollectionFactory::getCollection($alias);

			// if there are any collection aliases in the search that we do not
			// have access to, bail out
			if (!$this->isAuthorizedToSearch()) {
				throw new DMSecurityException(
					DMLocalizedString::getString("ACCESS_DENIED_TO_COL"));
			}

			$query = $this->getQueryFromURI(
					DMHTTPRequest::getCurrent()->getURI());
			$query->getSearchResults();

			$path = "/templates/object/results.html.php";
			$path = $query->getNumResults()
					? $path : "/templates/object/no_results.html.php";

			$tpl = $ts->getTemplateAtPathname($path);
			global $view;
			$view = new DMResultsView($tpl, $this->getSession(),
					$specified_collection, $query);
			$this->getSession()->setResultsView($view);

			$response = new DMHTTPResponse();
			$rep = DMHTTPResponseFactory::getRepresentation();
			$rep->setMediaType(new DMMediaType("text", "html"));
			$response->setRepresentation($rep);
			$response->send();
		} catch (DMException $e) {
			if (!$this->getTemplateSet()) {
				throw $e;
			}
			$tpl = $this->getTemplateSet()->getTemplateAtPathname(
					"/templates/error/view.html.php");
			global $view;
			$view = new DMSystemErrorView($tpl, $this->getSession(), $e);
			return;
		}
	}

	private function getQueryFromURI(DMInternalURI $uri) {
		$example_obj = new UNLVSpatialRectObject();
		$example_obj->setSpatialNorthLat((float) $uri->getQueryValue("lat_n"));
		$example_obj->setSpatialSouthLat((float) $uri->getQueryValue("lat_s"));
		$example_obj->setSpatialWestLong((float) $uri->getQueryValue("long_w"));
		$example_obj->setSpatialEastLong((float) $uri->getQueryValue("long_e"));

		$term = new UNLVSpatialQueryTerm();
		$term->setExampleObject($example_obj);

		switch ($uri->getQueryValue("mode")) {
		case "intersect":
			$term->setMatchingMode("intersect");
			break;
		case "outside":
			$term->setMatchingMode("outside");
			break;
		default:
			$term->setMatchingMode("within");
			break;
		}

		$query = new UNLVSpatialQuery();
		$query->addQueryTerm($term);

		$aliases = $uri->getQueryValue("CISOROOT");
		if (is_array($aliases)) {
			if (in_array("all", $aliases)) {
				$query->addCollection(DMCollectionFactory::getCollection("/dmdefault"));
			} else {
				foreach ($aliases as $alias) {
					$collection = DMCollectionFactory::getCollection(
							DMCollection::getSanitizedAlias($alias));
					$query->addCollection($collection);
				}
			}
		}

		$page = (int) $uri->getQueryValue("page");
		$rpp = (int) $uri->getQueryValue("rpp");
		$page = ($page < 1) ? 1 : $page;
		$rpp = ($rpp > 500) ? 500 : $rpp;
		$rpp = ($rpp < 10) ? 50 : $rpp;
		$query->setPage($page);
		$query->setNumResultsPerPage($rpp);
		return $query;
	}

	public function view($aliasptr) {
		$tmp = explode(",", $aliasptr);

		$col = DMCollectionFactory::getCollection(
				DMCollection::getSanitizedAlias($tmp[0]));
		$obj = self::getDataStore()->getObject($col, (int) $tmp[1]);
		if (!$obj) {
			throw new DMUnavailableModelException(
					DMLocalizedString::getString("NONEXISTENT_OBJECT"));
		}

		$response = new DMHTTPResponse();
		$rep = DMHTTPResponseFactory::getRepresentation();
		$response->setRepresentation($rep);
		try {
			$trans = DMHTTPResponseFactory::getTransformer();
			$rep->setBody($trans->transformObject($obj));
		} catch (DMException $e) {
			$response->setStatusCode($e->getHTTPResponseCode());
			$rep->setBody($e->getMessage());
		}
		$response->send();
		die;
	}

}
